# -*- coding: utf-8 -*-
"""
Created on Tue Jul  5 20:24:32 2016

@author: Administrator
"""
from stock import config
import os
echart_path= config.get_echart_path()

"""
import config
user, pwd, ip, db, tns = config.get_orcl_conn_var()
conn = orcl.oracle_conn(user=user, pwd=pwd, ip=ip, db=db)

sql = "select dates,open,high,low,close,close as ema from stock_qx where code='sh600000' and rownum<=100 order by dates asc"

data = pd.read_sql(sql,conn)
data.columns = [col.lower() for col in data.columns]
code = 'hehehehe'

"""

def k_line(code,data):
    '''使用百度echart绘制K线图。
    要求data的字段和顺序是：dates,open,close,lowest,highest,ema
    '''
    data = data[['dates','open','close','low','high','ema']]  # 字段重新排序
    df = data.sort_values('dates')
    # 将日期转成特定字符串格式2015-05-12
    df['dates'] = df['dates'].apply(lambda s:pd.to_datetime(s))
    df['dates'] = df['dates'].apply(lambda s:s.strftime("'%Y-%m-%d'"))
    # 将 dates,open,high,low,close转成字符串
    df2 = []
    for i in range(len(df)):
        a = [str(line) for line in df.iloc[i]]
        b = ','.join(a)
        df2.append(b)
    open_close = '],\n['.join(df2)
    open_close = '[['+open_close+']]'
    # 将ema转成列表格式
    if 'ema' not in df.columns:
        df['ema'] = df['close']
    ema = []
    a = [str(line) for line in df['ema']]
    b = ','.join(a)
    ema.append(b)
    ema = ','.join(ema)
    ema = '['+ema+']'
    # 替换模板生成k线图
    template = os.path.join(echart_path,'kline_template.html')
    kline = os.path.join(echart_path,'kline.html')
    # 读取模板
    f = open(template,'r',encoding='utf8')
    html = f.readlines()
    html = ''.join(html)
    f.close()
    #替换模板
    html2 = html.replace('limit_my_data',open_close)
    html2 = html2.replace('limit_my_ema_data',ema)
    html2 = html2.replace('limit_code',code)
    # 写到文件
    f = open(kline,'w',encoding='utf8')
    f.writelines(html2)
    f.close()

